//
//  AppDelegate.m
//  THJXHW
//
//  Created by 河南德艺 on 17/3/7.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "AppDelegate.h"
#import "LBTabBarController.h"
#define LBKeyWindow [UIApplication sharedApplication].keyWindow
#import "THJGuideVC.h"
//#import <BaiduMapAPI_Map/BMKMapView.h>
#import <GTSDK/GeTuiSdk.h> 
#import "JPNavigationController.h"
#define kGtAppId           @"buHccaSJqP6X4QuH2JYKL"
#define kGtAppKey          @"QfDT6hL0Ll95QFBdvIuve9"
#define kGtAppSecret       @"PAsfy0evwS6IxK5F5pNWW4"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif
//taskId=OSA-0512_Ecvl6sdErM9RpgoWkParo,messageId:c9738517-de5-15bf788d3e3-60465754,payloadMsg:{"id":36205,"title":"硅铁75#全国询盘报价","body":"牌号涨跌备注75#--现金含税75#--现金含税75#--现金含税75#--现金...","type":"21"}
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//微信SDK头文件
#import "WXApi.h"


#import <AVFoundation/AVFoundation.h>
//收到通知的View
#import "THJReceivePushMsgView.h"
//通知详情的webview
#import "THJWebviewVC.h"
//友盟统计
//#import "UMMobClick/MobClick.h"
#import <Security/Security.h>
#import <SAMKeychain.h>
#import "THJTabBarController.h"
#import "THJNewsDetailVC.h"


@interface AppDelegate ()<UIApplicationDelegate, GeTuiSdkDelegate, UNUserNotificationCenterDelegate,THJReceivePushMsgViewDelegate>
{
//    BMKMapManager * _mapManager;
    NSString * payloadMsg;
    NSString * msgType;
    NSString * msgTitle;
    NSString * msgID;
}
@property(nonatomic,strong)THJReceivePushMsgView * pushView;
@end

@implementation AppDelegate

-(THJReceivePushMsgView*)pushView{
    
    if (!_pushView) {
        _pushView = [THJReceivePushMsgView instancView];
    }
    return _pushView;
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    [self launchSetting];
    [self GeTuiSetting];
    [self shareSDKSetting];
    [self setBackWork];
    [self setUUidToKeychain];
    NSLog(@"qidong-%@",launchOptions);
    NSString * version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11.0) { // iOS系统版本 >= 11.0
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        UITableView.appearance.estimatedRowHeight = 0;
        UITableView.appearance.estimatedSectionHeaderHeight = 0;
        UITableView.appearance.estimatedSectionFooterHeight = 0;
    }
    return YES;
}
-(void)setUUidToKeychain{
    //从钥匙串读取UUID：
    NSString *retrieveuuid = [SAMKeychain passwordForService:@"com.henandeyi.app"account:@"user"];
    NSLog(@"keychain-%@",retrieveuuid);
    if(!retrieveuuid){
        //保存一个UUID字符串到钥匙串：
        CFUUIDRef uuid = CFUUIDCreate(NULL);
        assert(uuid != NULL);
        CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
        [SAMKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                      forService:@"com.henandeyi.app"account:@"user"];
    }
}
-(void)setBackWork{
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance]
     setCategory: AVAudioSessionCategoryPlayback
     error: &setCategoryErr];
    [[AVAudioSession sharedInstance]
     setActive: YES
     error: &activationErr];
}
-(void)launchWithlogin{

//    NSString * pwd = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
//    NSLog(@"lanuchstingPwd--%@",pwd);
//    if (pwd.length>0){
//       NSString * username = [[NSUserDefaults standardUserDefaults] objectForKey:@"MOBILE"];
//        NSString * urlStr = [NSString stringWithFormat:@"%@%@",THJDomain,@"user.php"];
//        //__weak typeof(self) weakself = self;
//        NSDictionary * dic = @{
//                               @"name":username,
//                               @"password":pwd,
//                               @"action":@"login"
//                               };
//        NSLog(@"lanuchstingUrl--%@",urlStr);
//        [THJNetWork postLoginFromUrl:urlStr parameters:dic callback:^(NSDictionary* receiveData, NSError *error) {
//            NSLog(@"###--%@",receiveData);
//
//           // [MBProgressHUD hideHUDForView:self.view animated:YES];
//            if(!error){
//                if ([receiveData[@"status"] isEqual:@"fail"]) {
//                   // [weakself HUDShowMsg:receiveData[@"msg"] AfterDelayDimiss:1];
//                }else if ([receiveData[@"status"] isEqual:@"success"]){
//                    //[weakself HUDShowMsg:@"登录成功" AfterDelayDimiss:2];
//                    [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"token"] forKey:@"token"];
//                    [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"name"] forKey:@"username"];
//                   // [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"password"] forKey:@"password"];
//                    if(!receiveData[@"hjb_type"]||[receiveData[@"hjb_type"] isEqual:[NSNull null]]){
//                        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"hjb_type"];
//                    }else{
//                        [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"hjb_type"] forKey:@"hjb_type"];
//                    }
//                    if(!receiveData[@"hjb_user"]||[receiveData[@"hjb_user"] isEqual:[NSNull null]]){
//                        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"hjb_user"];
//                    }else{
//                        [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"hjb_user"] forKey:@"hjb_user"];
//                    }
//                    if(!receiveData[@"hjb_money"]||[receiveData[@"hjb_money"] isEqual:[NSNull null]]){
//                        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"hjb_money"];
//                    }else{
//                        [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"hjb_money"] forKey:@"hjb_money"];
//                    }
//                    [[NSUserDefaults standardUserDefaults] setObject:receiveData[@"z_member_type"] forKey:@"z_member_type"];
//                    //第一次登录 存入YES
//                    [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"firstlogin"];
//                }
//            }
//        }];
//    }
}
-(void)launchSetting{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    THJTabBarController *tabBarVc = [THJTabBarController sharedTabBarC];
//    LBTabBarController * tabBarVc = [LBTabBarController sharedTabBarC];
    // 设置一个自定义 View,大小等于 tabBar 的大小
    UIView *bgView = [[UIView alloc] initWithFrame:tabBarVc.tabBar.bounds];
    
    // 给自定义 View 设置颜色
    bgView.backgroundColor = COLOR(65, 66, 67, 1);
    // 将自定义 View 添加到 tabBar 上
    [tabBarVc.tabBar insertSubview:bgView atIndex:0];
    
    THJGuideVC * guideVc = [[THJGuideVC alloc] init];
    NSString * string = [[NSUserDefaults standardUserDefaults] objectForKey:@"firstLangch"];
    //如果是第一次启动
    if ([string isEqual:@"first"]){
        self.window.rootViewController = tabBarVc;
    }else{
        self.window.rootViewController = guideVc;
    }
    [self.window makeKeyAndVisible];
    //  第一次启动  存入标识
    [[NSUserDefaults standardUserDefaults] setObject:@"first" forKey:@"firstLangch"];
}
-(void)GeTuiSetting{
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNs
    [self registerRemoteNotification];
    
   
}
-(void)shareSDKSetting{
    //shareSDK
    [ShareSDK registerApp:@"1d0e65c2cadb0"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ)
                            ]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wxde840f206a1798c5"
                                       appSecret:@"043ab1fc1330961b063eebed05169564"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1105963442"
                                      appKey:@"kLQvwXgRkaxEHR38"
                                    authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];
}

/** 注册 APNs */
- (void)registerRemoteNotification{
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}
/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [GeTuiSdk registerDeviceTokenData:deviceToken];
}
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}
/** APP已经接收到“远程”通知(推送) - 透传推送消息  */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 处理APNs代码，通过userInfo可以取到推送的信息（包括内容，角标，自定义参数等）。如果需要弹窗等其他操作，则需要自行编码。
    NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n",userInfo);
    // 将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    //根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}
//  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSLog(@"didReceiveNotification：%@", response);
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    completionHandler();
    
    [THJTabBarController sharedTabBarC].selectedIndex = 0;
    NSDictionary * msgDic = response.notification.request.content.userInfo;
    NSLog(@"didReceiveNotification2：%@", msgDic);
    if (msgDic[@"id"] && msgDic[@"type"]) {
        msgID = msgDic[@"id"];
        msgType = msgDic[@"type"];
        
        THJNewsDetailVC * vc = [[THJNewsDetailVC alloc] init];
       // ULog(@"**%@**",msgType);
        if ([msgType integerValue] == 21) {
            msgType = @"0";//行情
        }
        if([msgType integerValue] == 5){
            msgType = @"1";//供应
        }
        if([msgType integerValue] == 31){
            //      msgType = @"1";//现货
        }
        if([msgType integerValue] == 6){
            msgType = @"2";//求购
        }
        if([msgType integerValue] == 17){
            msgType = @"5";//团购
        }
        if([msgType integerValue] == 43){
            msgType = @"3";//招标
        }
        if([msgType integerValue] == 30){
            msgType = @"3";//招标
        }
        if([msgType isEqual:@"31"]){
            vc.url = @"http://www.thjb.net/";
        }
        vc.url =[NSString stringWithFormat:@"http://thjb.net/app/api/sharepage.php?itemid=%@&type=%@&from=singlemessage&isappinstalled=1",msgID,msgType];
        if([msgType isEqual:@"31"]){
            vc.url = @"http://www.thjb.net/";
        }
        vc.newsTitle = msgDic[@"aps"][@"alert"][@"title"];
        vc.newsContent = msgDic[@"aps"][@"alert"][@"body"];
        vc.itemid = msgType;
        vc.mid = msgID;
        vc.flag = YES;
        [[THJTabBarController sharedTabBarC] presentViewController:vc animated:YES completion:nil];
    }
}
#endif
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}
/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    //个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}
/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
    payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    NSDictionary * msgDic = [NSJSONSerialization JSONObjectWithData:payloadData options:NSJSONReadingMutableLeaves error:nil];
    NSLog(@"msgDic--%@",msgDic);
    msgType = msgDic[@"type"];
    msgTitle = msgDic[@"title"];
    msgID = msgDic[@"id"];
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
    //消息提醒框
    if(!offLine){
        self.pushView.delegate = self;
        self.pushView.backgroundColor = COLOR(0, 0, 0, 0.3);
        self.pushView.frame = self.window.frame;
        [self.window addSubview:self.pushView];
    }
}
//点击消息提醒框 立即前往
-(void)goToReceivePushMsgDetail{
    NSLog(@"立即前往");
    THJWebviewVC * vc = [[THJWebviewVC alloc] init];
    vc.titleStr = msgTitle;
    vc.IsComeFromPush = YES;
    if ([msgType isEqual:@"21"]) {
        msgType = @"0";//行情
    }else if([msgType isEqual:@"5"]){
        msgType = @"1";//供应
    }else if([msgType isEqual:@"31"]){
//      msgType = @"1";//现货
    }else if([msgType isEqual:@"6"]){
        msgType = @"2";//求购
    }else if([msgType isEqual:@"17"]){
        msgType = @"5";//团购
    }else if([msgType isEqual:@"43"]){
        msgType = @"3";//资讯招标
    }else if([msgType isEqual:@"30"]){
        msgType = @"3";//材料招标
    }else if([msgType isEqual:@"show"]){
        msgType = @"4";//专题
    }
    vc.detailUrl =[NSString stringWithFormat:@"%@sharepage.php?itemid=%@&type=%@&from=singlemessage&isappinstalled=1",THJDomain,msgID,msgType];
    if([msgType isEqual:@"31"]){
        vc.detailUrl = @"http://www.thjb.net/";
    }
    UINavigationController * nvc = [[UINavigationController alloc] initWithRootViewController:vc];
    [[THJTabBarController sharedTabBarC] presentViewController:nvc animated:YES completion:nil];
}
-(void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
}
- (void)applicationWillTerminate:(UIApplication *)application {
    //Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
